
package com.tim.app.server.logic;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.application.library.log.DLOG;
import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.ActivityManager;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.FileUtils;
import com.google.gson.Gson;
import com.netease.nim.DemoCache;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.msg.MsgService;
import com.qiyukf.unicorn.api.Unicorn;
import com.tim.app.RT;
import com.tim.app.constant.EventTag;
import com.tim.app.db.dao.DaoFactory;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.User;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.MainActivity;
import com.tim.app.util.PreferenceHelper;
import com.tim.app.util.ToastUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class UserManager {
    private static final String TAG = "UserManager";

    private static final String KEY_USER_INFO = "key_user_info";//缓存用户信息
    private static final String KEY_LOGIN_TOKEN = "key_login_token";//登陆token
    public static final String LAST_SIGN_TIME = "last_sign_time";//上次签到时间
    private static final String KEY_LOGIN_TYPE = "loginType";//登录的类型
    private static final String HTTP_SERVER_DOMAIN = "http_domain";//http的服务器域名
    private static final String ACCESS_TOKEN = "accessToken";//accessToken
    private static final String KEY_SEARCH_HISTORY = "searchHistory";//搜索记录
    private static final String OFFICIAL_UNREAD_COUNT = "unreadOfficialMessageCount";//未读的官方通知

    private static final String BANNER_VERSION = "bannerVersion";//banner的版本
    private static final String HOT_SPECIAL_VERSION = "specialVersion";//专题的版本
    private static final String EVERY_MUSIC_VERSION = "everyMusicVersion";//每日一听的版本
    private static final String ALBUM_VERSION = "albumVersion";//专辑的版本

    private static final String BANNER_UPDATE_FLAG = "bannerUpdateFlag";//banner更新标识
    private static final String HOT_SPECIAL_UPDATE_FLAG = "hotSpecialUpdateFlag";//热门专题更新标识
    private static final String EVERY_MUSIC_UPDATE_FLAG = "evertMusicUpdateFlag";//每日一听更新标识
    private static final String ALBUM_UPDATE_FLAG = "albumUpdateFlag";//专辑更新标识

    private static UserManager mUserManager;

    private UserManager() {

    }

    public static UserManager ins() {
        if (mUserManager == null) {
            mUserManager = new UserManager();
        }
        return mUserManager;
    }

    User currentUser = new User();

    /**
     * 判断是否登录
     *
     * @return
     */
    public boolean isLogin() {
        return (null != currentUser) && !TextUtils.isEmpty(currentUser.getId());
    }

    /**
     * 返回环信的ID
     *
     * @param userId
     * @return
     */
    public String getChatId(String userId) {
        if (userId.contains("moli")) {
            return userId;
        } else {
            return "moli" + userId;
        }
    }

    /**
     * 返回当前登录用户
     *
     * @return
     */
    public User getLoginUser() {
        return currentUser;
    }

    /**
     * 返回当前登录用户的id
     *
     * @return
     */
    public String getUserId() {
        String uid = "";
        if (isLogin()) {
            uid = currentUser.getId();
        }
        return uid;
    }

    /**
     * 获取登录类型
     *
     * @return
     */
    public String getLoginType() {
        return PreferenceHelper.ins().getStringShareData(KEY_LOGIN_TYPE, "");
    }

    public void saveLoginType(String type) {
        PreferenceHelper.ins().storeShareStringData(KEY_LOGIN_TYPE, type);
        PreferenceHelper.ins().commit();
    }

    /**
     * 注销 清空数据 发送注销事件
     */
    public void logout(Context context) {
        saveLoginType("");
        saveUserInfo(null);
        DaoFactory.clearDataAll(context);
        new Thread(new Runnable() {
            @Override
            public void run() {
                FileUtils.deleteFile(RT.defaultCache);
                Unicorn.clearCache();
            }
        }).start();

        EventManager.ins().sendEvent(EventTag.ACCOUNT_LOGOUT, 0, 0, null);
        try {
            File file = new File(RT.defaultCache);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Unicorn.logout();// 七鱼登出
        NIMClient.getService(AuthService.class).logout();//云信登出
        NIMClient.getService(MsgService.class).clearMsgDatabase(true);

        JPushInterface.setAlias(context, "", new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {

            }
        });
        UserManager.ins().saveLastSign("");
        ActivityManager.ins().finishAllActivity();
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("isGogoToLogin", true);
        context.startActivity(intent);
    }

    /**
     * 登录云信
     *
     * @param userId
     */
    public void loginYX(String userId) {
        final String value = getChatId(userId);
        LoginInfo info = new LoginInfo(value, value); // config...
        RequestCallback<LoginInfo> callback =
                new RequestCallback<LoginInfo>() {
                    @Override
                    public void onSuccess(LoginInfo loginInfo) {
                        DemoCache.setAccount(value);
                        DLOG.e("===", "onSccess");
                    }

                    @Override
                    public void onFailed(int i) {
                        DLOG.e("===", "onFailed" + i);
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        throwable.printStackTrace();
                    }
                    // 可以在此保存LoginInfo到本地，下次启动APP做自动登录用
                };
        NIMClient.getService(AuthService.class).login(info)
                .setCallback(callback);
    }

    /**
     * 保存用户信息
     */
    public void saveUserInfo(User user) {
        try {
            this.currentUser = user;
            if (currentUser != null) {
                currentUser.setUserId(currentUser.getId());
                String content = new Gson().toJson(currentUser);
                PreferenceHelper.ins().storeShareData(KEY_USER_INFO, content.getBytes("UTF-8"), true);
                PreferenceHelper.ins().commit();
            } else {
                PreferenceHelper.ins().storeShareStringData(KEY_USER_INFO, "");
                PreferenceHelper.ins().commit();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取用户信息
     */
    public void loadUserInfo(LoadCallBack callBack) {
        try {
            // 从手机内存中读取
            String content = PreferenceHelper.ins().getStringShareData(KEY_USER_INFO, "");
            if (!TextUtils.isEmpty(content)) {
                currentUser = new Gson().fromJson(content, User.class);
                currentUser.setUserId(currentUser.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != callBack) {
                callBack.onComlpete();
            }
        }
    }

    public interface LoadCallBack {

        void onComlpete();

    }

    public void cleanCache() {
        FileUtils.deleteFile(RT.defaultCache);
        FileUtils.deleteFile(RT.defaultImage);
        try {
            File file = new File(RT.defaultCache);
            if (!file.exists()) {
                file.mkdirs();
            }
            File image = new File(RT.defaultImage);
            if (!image.exists()) {
                image.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void cleanImageCache() {
        FileUtils.deleteFile(RT.defaultImage);
        try {
            File image = new File(RT.defaultImage);
            if (!image.exists()) {
                image.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存登陆token
     *
     * @param token
     */
    public void saveToken(String token) {
        PreferenceHelper.ins().storeShareStringData(KEY_LOGIN_TOKEN, token);
        PreferenceHelper.ins().commit();
    }

    /**
     * 保存上次签到时间
     *
     * @param time
     */
    public void saveLastSign(String time) {
        PreferenceHelper.ins().storeShareStringData(LAST_SIGN_TIME, time);
        PreferenceHelper.ins().commit();
    }

    public String getValue(String key) {
        return PreferenceHelper.ins().getStringShareData(key, "");
    }

    public String getToken() {
        return PreferenceHelper.ins().getStringShareData(KEY_LOGIN_TOKEN, "");
    }

    /**
     * 获取http的服务器域名
     *
     * @return
     */
    public String getHttpServerDomain() {
        return PreferenceHelper.ins().getStringShareData(UserManager.HTTP_SERVER_DOMAIN, "");
    }

    /**
     * 获取accessToken
     *
     * @return
     */
    public String getAccessToken() {
        return PreferenceHelper.ins().getStringShareData(UserManager.ACCESS_TOKEN, "");
    }

    /**
     * 保存http的服务器域名
     *
     * @param httpServerDomain
     */
    public void saveHttpServerDomain(String httpServerDomain) {
        PreferenceHelper.ins().storeShareStringData(UserManager.HTTP_SERVER_DOMAIN, httpServerDomain);
        PreferenceHelper.ins().commit();
    }

    /**
     * 获取未读的官方通知数量
     *
     * @return
     */
    public int getUnreadOfficialMessageCount() {
        return PreferenceHelper.ins().getIntShareData(UserManager.OFFICIAL_UNREAD_COUNT, 0);
    }

    /**
     * 更新官方通知数量
     *
     * @param count
     */
    public void updateUnreadOfficialMessageCount(int count) {
        PreferenceHelper.ins().storeIntShareData(UserManager.OFFICIAL_UNREAD_COUNT, count);
        PreferenceHelper.ins().commit();
    }

    /**
     * 保存accessToken
     *
     * @param accessToken
     */
    public void saveAccessToken(String accessToken) {
        PreferenceHelper.ins().storeShareStringData(UserManager.ACCESS_TOKEN, accessToken);
        PreferenceHelper.ins().commit();
    }

    /**
     * 保存搜索历史
     *
     * @param searchHistory
     */
    public void saveSearchHistory(List<String> searchHistory) {
        if (null == searchHistory)
            return;
        StringBuffer data = new StringBuffer();
        if (searchHistory.size() != 0) {
            for (int i = 0; i < searchHistory.size(); i++) {
                if (i != searchHistory.size() - 1) {
                    data.append(searchHistory.get(i) + "#");
                } else {
                    data.append(searchHistory.get(i));
                }
            }
        }
        PreferenceHelper.ins().storeShareStringData(UserManager.KEY_SEARCH_HISTORY, data.toString());
        PreferenceHelper.ins().commit();
    }


    /**
     * 返回新的搜索历史记录
     *
     * @param keyword
     * @return
     */
    public List<String> addSearchHistory(String keyword) {
        List<String> searchHistory = getSearchHistory();
        if (searchHistory.size() > 0) {
            for (int i = 0; i < searchHistory.size(); i++) {
                if (searchHistory.get(i).equals(keyword)) {
                    searchHistory.remove(i);
                    break;
                }
            }
        }
        searchHistory.add(0, keyword);
        if (searchHistory.size() > 30) {
            searchHistory = searchHistory.subList(0, 30);
        }
        UserManager.ins().saveSearchHistory(searchHistory);
        return searchHistory;
    }

    /**
     * 获取搜索历史
     *
     * @return
     */
    public List<String> getSearchHistory() {
        List<String> hotWords = new ArrayList<>();
        String saveInfo = PreferenceHelper.ins().getStringShareData(UserManager.KEY_SEARCH_HISTORY, "");
        if (!TextUtils.isEmpty(saveInfo)) {
            String[] values = saveInfo.split("#");
            Collections.addAll(hotWords, values);
        }
        return hotWords;
    }

    /**
     * 增加历史记录
     *
     * @param tag
     * @param typeId
     * @param type
     */
    public void addBrowserHistory(String tag, String type, String typeId) {
        API_User.ins().addBrowserHistory(tag, type, typeId, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                return false;
            }
        });
    }

    /**
     * 登录聊天服务器
     *
     * @param userId
     */
    public void loginChat(String userId) {
        loginYX(userId);
    }

    /**
     * 显示登陆提示弹窗
     *
     * @param context
     */
//    public void showLoginDialog(final Context context) {
//        TipDialog dialog = new TipDialog(context);
//        dialog.setTextDes(context.getString(R.string.login_dialog_desc));
//        dialog.setButton1(context.getString(R.string.login_title), new TipDialog.DialogButtonOnClickListener() {
//            @Override
//            public void onClick(View button, TipDialog dialog) {
//                dialog.dismiss();
//                ViewGT.gotoLoginActivity(context);
//            }
//        });
//        dialog.setButton2(context.getString(R.string.action_cancel), new TipDialog.DialogButtonOnClickListener() {
//            @Override
//            public void onClick(View button, TipDialog dialog) {
//                dialog.dismiss();
//            }
//        });
//        dialog.show();
//    }

    /**
     * 举报
     *
     * @param TAG
     * @param type
     * @param typeId
     */
    public void report(String TAG, String type, String typeId) {
        API_User.ins().report(TAG, type, typeId, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK) {
                    ToastUtil.showToast("举报成功");
                } else if (errCode == ResponseResult.ResultStatus.REPEAT_ACTION) {
                    ToastUtil.showToast("你已经举报过了");
                } else {
                    ToastUtil.showToast("举报失败");
                }
                return false;
            }
        });
    }

    /**
     * 获取banner的版本
     *
     * @return
     */
    public int getBannerVersion() {
        return PreferenceHelper.ins().getIntShareData(UserManager.BANNER_VERSION, 0);
    }

    /**
     * 更新banner的版本信息
     *
     * @param newVersion
     */
    public void updateBannerVersion(int newVersion) {
        PreferenceHelper.ins().storeIntShareData(UserManager.BANNER_VERSION, newVersion);
        PreferenceHelper.ins().commit();
    }

    /**
     * 获取热门专题的版本
     *
     * @return
     */
    public int getHotSpecialVersion() {
        return PreferenceHelper.ins().getIntShareData(UserManager.HOT_SPECIAL_VERSION, 0);
    }

    /**
     * 更新热门专题的版本信息
     *
     * @param newVersion
     */
    public void updateHotSpecialVersion(int newVersion) {
        PreferenceHelper.ins().storeIntShareData(UserManager.HOT_SPECIAL_VERSION, newVersion);
        PreferenceHelper.ins().commit();
    }

    /**
     * 获取每日一听的版本
     *
     * @return
     */
    public int getEveryMusicVersion() {
        return PreferenceHelper.ins().getIntShareData(UserManager.EVERY_MUSIC_VERSION, 0);
    }

    /**
     * 更新每日一听的版本信息
     *
     * @param newVersion
     */
    public void updateEveryMusicVersion(int newVersion) {
        PreferenceHelper.ins().storeIntShareData(UserManager.EVERY_MUSIC_VERSION, newVersion);
        PreferenceHelper.ins().commit();
    }

    /**
     * 获取专辑的版本
     *
     * @return
     */
    public int getAlbumVersion() {
        return PreferenceHelper.ins().getIntShareData(UserManager.ALBUM_VERSION, 0);
    }

    /**
     * 更新专辑的版本信息
     *
     * @param newVersion
     */
    public void updateAlbumVersion(int newVersion) {
        PreferenceHelper.ins().storeIntShareData(UserManager.ALBUM_VERSION, newVersion);
        PreferenceHelper.ins().commit();
    }

    /**
     * 获取banner的更新状态
     *
     * @return
     */
    public boolean getBannerUpdateState() {
        return PreferenceHelper.ins().getBooleanShareData(UserManager.BANNER_UPDATE_FLAG, false);
    }

    /**
     * 更新banner的更新状态
     *
     * @param state
     */
    public void updateBannerUpdateState(boolean state) {
        PreferenceHelper.ins().storeBooleanShareData(UserManager.BANNER_UPDATE_FLAG, state);
        PreferenceHelper.ins().commit();
    }

    /**
     * 获取HotSpecial的更新状态
     *
     * @return
     */
    public boolean getHotSpecialUpdateState() {
        return PreferenceHelper.ins().getBooleanShareData(UserManager.HOT_SPECIAL_UPDATE_FLAG, false);
    }

    /**
     * 更新HotSpecial的更新状态
     *
     * @param state
     */
    public void updateHotSpecialUpdateState(boolean state) {
        PreferenceHelper.ins().storeBooleanShareData(UserManager.HOT_SPECIAL_UPDATE_FLAG, state);
        PreferenceHelper.ins().commit();
    }

    /**
     * 获取每日一听的更新状态
     *
     * @return
     */
    public boolean getEveryMusicUpdateState() {
        return PreferenceHelper.ins().getBooleanShareData(UserManager.EVERY_MUSIC_UPDATE_FLAG, false);
    }

    /**
     * 更新每日一听的更新状态
     *
     * @param state
     */
    public void updateEveryMusicUpdateState(boolean state) {
        PreferenceHelper.ins().storeBooleanShareData(UserManager.EVERY_MUSIC_UPDATE_FLAG, state);
        PreferenceHelper.ins().commit();
    }

    /**
     * 获取专辑的更新状态
     *
     * @return
     */
    public boolean getAlbumUpdateState() {
        return PreferenceHelper.ins().getBooleanShareData(UserManager.ALBUM_UPDATE_FLAG, false);
    }

    /**
     * 更新专辑的更新状态
     *
     * @param state
     */
    public void updateAlbumUpdateState(boolean state) {
        PreferenceHelper.ins().storeBooleanShareData(UserManager.ALBUM_UPDATE_FLAG, state);
        PreferenceHelper.ins().commit();
    }

}
